// -----------------------------------------------------------------------
//  <copyright file="RoleNameResolver.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-02-19 12:02</last-date>
// -----------------------------------------------------------------------

using System.Security.Claims;

using DaprPlus.Domain.Entity;
using DaprPlus.Identity;


namespace DaprPlus.Authorization;

/// <summary>
/// 默认角色名称解析器实现
/// </summary>
public class RoleNameResolver<TRole>(IRepository<TRole> repository)
    : IRoleNameResolver where TRole : class, IRole
{
    /// <summary>
    /// 从身份信息中获取角色名称列表并解析为角色ID列表
    /// </summary>
    public async Task<long[]> ResolveRoleIds(ClaimsIdentity identity)
    {
        var roleNames = identity.GetRoles();
        return await ResolveRoleIds(roleNames);
    }

    /// <summary>
    /// 从角色名称列表解析为角色ID列表
    /// </summary>
    public async Task<long[]> ResolveRoleIds(string[] roleNames)
    {
        if (roleNames.Length == 0) return [];
        var roles = await GetAllRoles();
        return roles.Where(m => roleNames.Contains(m.Name)).Select(m => m.Id).ToArray();
    }

    /// <summary>
    /// 从角色编号列表解析为角色名称列表
    /// </summary>
    /// <param name="roleIds">角色编号列表</param>
    /// <returns></returns>
    public async Task<string[]> ResolveRoleName(long[] roleIds)
    {
        if (roleIds.Length == 0)
        {
            return [];
        }

        var roles = await GetAllRoles();
        return roles.Where(m => roleIds.Contains(m.Id)).Select(m => m.Name).ToArray();
    }

    private async Task<List<TRole>> GetAllRoles()
    {
        var spec = new TrueSpecification<TRole>();
        return await repository.GetAllAsync(spec);
    }
}
